import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authService } from '@/services/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(null)
  const user = ref(null)
  const userRole = ref(null)
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isHR = computed(() => userRole.value === 'hr')
  const isCandidate = computed(() => userRole.value === 'candidate')

  // 方法
  const login = async (credentials) => {
    try {
      isLoading.value = true
      
      console.log('Auth store: 尝试登录...', { email: credentials.email, role: credentials.role })
      
      try {
        // 尝试真实登录
        const response = await authService.login(credentials)
        
        console.log('Auth store: 登录成功', { token: response.token ? '有token' : '无token', user: response.user })
        
        token.value = response.token
        user.value = response.user
        userRole.value = response.user.role
        
        // 存储到 localStorage
        localStorage.setItem('auth_token', response.token)
        localStorage.setItem('user_role', response.user.role)
        
        ElMessage.success('登录成功')
        return response
      } catch (error) {
        console.log('Auth store: 登录失败', error)
        
        // 如果是网络错误，使用模拟登录
        if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error') || 
            error.message.includes('ERR_NETWORK') || error.message.includes('fetch')) {
          ElMessage.warning('后端服务暂不可用，使用演示模式登录')
          
          // 模拟用户数据
          const mockUser = {
            id: 1,
            name: credentials.role === 'hr' ? 'HR管理员' : '测试候选人',
            email: credentials.email,
            role: credentials.role
          }
          
          const mockToken = 'mock-token-' + Date.now()
          
          token.value = mockToken
          user.value = mockUser
          userRole.value = mockUser.role
          
          // 存储到 localStorage
          localStorage.setItem('auth_token', mockToken)
          localStorage.setItem('user_role', mockUser.role)
          
          ElMessage.success('演示模式登录成功')
          return { token: mockToken, user: mockUser }
        } else {
          // 其他错误直接抛出，让上层处理
          throw error
        }
      }
    } catch (error) {
      console.error('Auth store: 登录过程出错', error)
      // 不在这里显示错误消息，让上层处理
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const register = async (userData) => {
    try {
      isLoading.value = true
      
      try {
        // 尝试真实注册
        const response = await authService.register(userData)
        
        console.log('Auth store: 注册API响应:', response)
        
        // 验证响应数据结构
        if (!response) {
          throw new Error('注册响应为空')
        }
        
        // 处理不同的响应格式
        let userInfo = null
        let authToken = null
        
        if (response.user && response.token) {
          // 标准格式：{ user: {...}, token: "..." }
          userInfo = response.user
          authToken = response.token
        } else if (response.token && !response.user) {
          // 只有token，没有user信息，需要构造用户信息
          authToken = response.token
          userInfo = {
            id: Date.now(),
            name: userData.name,
            email: userData.email,
            role: userData.role,
            phone: userData.phone || ''
          }
        } else if (response.id) {
          // 直接返回用户信息，没有token
          userInfo = {
            id: response.id,
            name: response.name || userData.name,
            email: response.email || userData.email,
            role: response.role || userData.role,
            phone: response.phone || userData.phone || ''
          }
          authToken = 'token-' + response.id // 生成临时token
        } else {
          // 其他格式，尝试从response直接提取
          userInfo = {
            id: response.id || Date.now(),
            name: response.name || userData.name,
            email: response.email || userData.email,
            role: response.role || userData.role,
            phone: response.phone || userData.phone || ''
          }
          authToken = response.token || 'token-' + Date.now()
        }
        
        // 确保用户信息完整
        if (!userInfo.role) {
          userInfo.role = userData.role
        }
        
        console.log('Auth store: 处理后的用户信息:', userInfo)
        console.log('Auth store: 处理后的token:', authToken ? '有token' : '无token')
        
        token.value = authToken
        user.value = userInfo
        userRole.value = userInfo.role
        
        // 存储到 localStorage
        localStorage.setItem('auth_token', authToken)
        localStorage.setItem('user_role', userInfo.role)
        
        ElMessage.success('注册成功')
        return { token: authToken, user: userInfo }
        
      } catch (error) {
        console.error('Auth store: 注册失败', error)
        
        // 如果是网络错误，使用模拟注册
        if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
          ElMessage.warning('后端服务暂不可用，使用演示模式注册')
          
          // 模拟用户数据
          const mockUser = {
            id: Date.now(),
            name: userData.name,
            email: userData.email,
            role: userData.role,
            phone: userData.phone
          }
          
          const mockToken = 'mock-token-' + Date.now()
          
          token.value = mockToken
          user.value = mockUser
          userRole.value = mockUser.role
          
          // 存储到 localStorage
          localStorage.setItem('auth_token', mockToken)
          localStorage.setItem('user_role', mockUser.role)
          
          ElMessage.success('演示模式注册成功')
          return { token: mockToken, user: mockUser }
        } else {
          throw error
        }
      }
    } catch (error) {
      console.error('Auth store: 注册过程出错', error)
      ElMessage.error(error.message || '注册失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  const logout = async () => {
    try {
      await authService.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除状态
      token.value = null
      user.value = null
      userRole.value = null
      
      // 清除本地存储
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_role')
      
      ElMessage.success('已退出登录')
    }
  }

  const checkAuthStatus = async () => {
    const storedToken = localStorage.getItem('auth_token')
    const storedRole = localStorage.getItem('user_role')
    
    if (storedToken) {
      token.value = storedToken
      userRole.value = storedRole
      
      try {
        // 验证 token 有效性
        const response = await authService.verifyToken()
        user.value = response.user
      } catch (error) {
        // token 无效，清除状态
        await logout()
      }
    }
  }

  return {
    // 状态
    token,
    user,
    userRole,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    isHR,
    isCandidate,
    
    // 方法
    login,
    register,
    logout,
    checkAuthStatus
  }
}) 